package com.toKnow.listener;

import com.alibaba.druid.pool.DruidDataSource;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.sql.DriverManager;
import java.sql.SQLException;

@WebListener
public class ContextFinalizer implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
    }

    //不加以下代码tomcat关闭时会报错
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //取消注册JDBC驱动程序
        try {
            while (DriverManager.getDrivers().hasMoreElements()) {
                DriverManager.deregisterDriver(DriverManager.getDrivers().nextElement());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // 关闭[Abandoned connection cleanup thread]的线程
        try {
            AbandonedConnectionCleanupThread.shutdown();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //获取spring容器
        WebApplicationContext ctx =
                WebApplicationContextUtils.getRequiredWebApplicationContext(servletContextEvent.getServletContext());
        //关闭数据库连接池
        DruidDataSource druidDataSource = (DruidDataSource) ctx.getBean("myDataSource");
        druidDataSource.close();
    }
}
